#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <fcntl.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Log.hpp"

#define MAX_LISTEN 1024 // 同一时间的最大并发连接数
class Sock
{
private:
    int _sockfd = -1;

    // 创建套接字
    bool Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (_sockfd < 0)
        {
            ERR_LOG("create socket failed!");
            return false;
        }
        INF_LOG("[create socket success]");
        return true;
    }
    // 绑定地址信息
    bool Bind(const std::string &ip, uint16_t port)
    {
        struct sockaddr_in tmp;
        tmp.sin_family = AF_INET;
        tmp.sin_port = htons(port);
        tmp.sin_addr.s_addr = inet_addr(ip.c_str());
        socklen_t len = sizeof(tmp);

        int ret = bind(_sockfd, (const sockaddr *)&tmp, len);
        if (ret < 0)
        {
            ERR_LOG("bind address failed!");
            return false;
        }
        INF_LOG("[bind address success]");
        return true;
    }
    // 开始监听
    bool Listen(int backlog)
    {
        int ret = listen(_sockfd, backlog);
        if (ret < 0)
        {
            ERR_LOG("listen sockfd failed!");
            return false;
        }
        INF_LOG("[listen sockfd .....]");
        return true;
    }
    // 向服务器发起连接
    bool Connect(const std::string &ip, uint16_t port)
    {
        struct sockaddr_in tmp;
        tmp.sin_family = AF_INET;
        tmp.sin_port = htons(port);
        tmp.sin_addr.s_addr = inet_addr(ip.c_str());
        socklen_t len = sizeof(tmp);

        int ret = connect(_sockfd, (const sockaddr *)&tmp, len);
        if (ret < 0)
        {
            ERR_LOG("connect server failed!");
            return false;
        }
        INF_LOG("[connect server success]");
        return true;
    }

public:
    // 接收数据
    ssize_t Recv(void *buf, size_t len, int flag = 0)
    {
        ssize_t ret = recv(_sockfd, buf, len, flag);
        if (ret <= 0)
        {
            // EAGAIN: 当前socket的接收缓冲区没有数据了（非阻塞情况）
            // EINTR：当前socket的阻塞等待被信号打断了
            if (errno == EAGAIN || errno == EINTR)
                return 0;
            ERR_LOG("sockfd recv failed!");
            return -1;
        }
        return ret;
    }
    // 发送数据
    ssize_t Send(void *buf, size_t len, int flag = 0)
    {
        ssize_t ret = send(_sockfd, buf, len, flag);
        if (ret < 0)
        {
            if (errno == EAGAIN || errno == EINTR)
                return 0;
            ERR_LOG("sockfd send failed!");
            return -1;
        }
        return ret;
    }
    // 设置套接字选项--开启地址端口重用
    void ReuseAddress()
    {
        int opt = 1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, (void *)&opt, sizeof(opt));
    }
    // 设置套接字属性为非阻塞
    void NonBlock()
    {
        int flag = fcntl(_sockfd, F_GETFL, 0);
        fcntl(_sockfd, F_SETFL, flag | O_NONBLOCK);
    }

    Sock(int sockfd = -1) : _sockfd(sockfd) {}
    ~Sock() { Close(); }
    // 获取文件描述符
    int Fd() { return _sockfd; }
    // 获取新连接
    int Accept()
    {
        int newsockfd = accept(_sockfd, nullptr, nullptr);
        if (newsockfd < 0)
        {
            ERR_LOG("socket accept failed!");
            return -1;
        }
        INF_LOG("[get a new link...]");
        return newsockfd;
    }
    // 非阻塞接收数据
    ssize_t NonBlockRecv(void *buf, size_t len)
    {
        return Recv(buf, len, MSG_DONTWAIT);
    }
    // 非阻塞发送数据
    ssize_t NonBlockSend(void *buf, size_t len)
    {
        if(len == 0) return 0;
        std::cout << (char*)buf << std::endl;
        return Send(buf, len, MSG_DONTWAIT);
    }
    // 关闭套接字
    void Close()
    {
        if (_sockfd != -1)
        {
            close(_sockfd);
            _sockfd = -1;
        }
    }
    // 创建一个服务端连接
    bool CreateServer(uint16_t port, bool flag = 1, const int backlog = MAX_LISTEN)
    {
        // 1.创建套接字 2.设置非阻塞 3.绑定ip和端口号 4.开始监听 5.启动地址重用
        if (Socket() == false)
            return false;
        if (flag)
            NonBlock();
        if (Bind("0.0.0.0", port) == false)
            return false;
        if (Listen(backlog) == false)
            return false;
        ReuseAddress();
        return true;
    }
    // 创建一个客户端连接
    bool CreateClient(const std::string &ip, uint16_t port)
    {
        // 1.创建套接字 2.指向连接服务器
        if (Socket() == false)
            return false;
        if (Connect(ip, port) == false)
            return false;
        return true;
    }
};
